package com.hmdp.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.CACHE_NULL_TTL;

@Component
public class CacheClient {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    public void set(String key, Object value, Long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(value), time, timeUnit);
    }

    public <R, ID> R getCache(String keyPrefix, ID id, Class<R> type, Function<ID,R> cacheLoader, Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String objectJson = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(objectJson)) {
            return JSONUtil.toBean(objectJson, type);
        }
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        R r = null;
        try {
            // double check
            if (StrUtil.isNotBlank(objectJson = stringRedisTemplate.opsForValue().get(key))) {
                return JSONUtil.toBean(objectJson, type);
            }
            // query db
            r = cacheLoader.apply(id);
            if (null == r) {
                // set null to avoid cache penetration
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            this.set(key, r, time, unit);
        } finally {
            lock.unlock();
        }
        return r;

    }
}
